<!--
 * @Descripttion: 
 * @version: 
 * @Author: sueRimn
 * @Date: 2023-11-01 09:18:41
 * @LastEditors: sueRimn
 * @LastEditTime: 2023-11-01 10:38:12
-->
<template>
  <div>
    <el-dialog
      :visible.sync="dialogTableVisible"
      :close-on-click-modal="false"
      @close="evtDialogClose"
      lock-scroll
      title="维修维护记录"
      width="900px"
      append-to-body
    >
      <div v-loading="tableLoading">
        <div class="win-warp" style="height: 530px">
          <el-container
            ref="listWarp"
            style="height: 100%; background-color: #fff"
          >
            <el-header style="height: 45px" class="headers">
              <div class="select">
                <!-- <el-date-picker
                  style="width: 200px"
                  v-model="searchObj.repairDate"
                  type="date"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择日期"
                  @change="getTableList()"
                  size="small"
                ></el-date-picker> -->
                <el-date-picker
                  size="small"
                  v-model="searchObj.dateData"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  style="width: 300px; margin-left: 10px"
                  @change="getTableList()"
                  :clearable="false"
                ></el-date-picker>
                <el-select
                  v-model="searchObj.typeId"
                  placeholder="维护类型"
                  size="small"
                  style="width: 200px"
                  @change="getTableList()"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in maintenanceTypeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </div>
              <div class="btns">
                <div class="add" @click="event('add')">
                  <svg-icon
                    icon-class="add"
                    style="font-size: 13px; margin-right: 5px"
                  />新增
                </div>
                <div class="edit" @click="event('edit')">
                  <svg-icon
                    icon-class="edit"
                    style="font-size: 13px; margin-right: 5px"
                  />

                  编辑
                </div>
                <div class="del" @click="event('del')">
                  <svg-icon
                    icon-class="delete"
                    style="font-size: 13px; margin-right: 5px"
                  />

                  删除
                </div>
              </div>
            </el-header>
            <el-main style="height: 100%; padding: 0">
              <el-table
                :data="tableData"
                height="100%"
                style="width: 100%"
                border
                v-loading="loading"
                highlight-current-row
                @row-dblclick="tableDbEdit"
                @current-change="evtTableRowChange"
                @selection-change="handleSelectionChange"
                ref="dataListTable"
              >
                <el-table-column type="selection" width="55" fixed="left">
                </el-table-column>
                <el-table-column
                  type="index"
                  width="50"
                  label="序号"
                  fixed="left"
                ></el-table-column>
                <el-table-column
                  prop="typeName"
                  label="维护类型"
                  fixed="left"
                ></el-table-column>
                <el-table-column prop="repairLog" label="维护记录">
                </el-table-column>
                <el-table-column
                  prop="repairUserName"
                  label="维护人"
                ></el-table-column>
                <el-table-column
                  prop="repairDate"
                  label="维护时间"
                ></el-table-column>
              </el-table>
            </el-main>
            <el-footer style="height: 45px" class="page-footer">
              <el-pagination
                style="padding-top: 8px"
                background
                layout="prev, pager, next,jumper,total,sizes"
                @size-change="evtPageSizeChange"
                @current-change="evtPageCurrentChange"
                :current-page.sync="currentPage"
                :page-sizes="[20, 50, 100, 500]"
                :total="totalRows"
              ></el-pagination>
            </el-footer>
          </el-container>
        </div>
        <!-- <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false" size="small"
            >取 消</el-button
          >
          <el-button @click="addBtn()" type="primary" size="small"
            >确定</el-button
          >
        </div> -->
      </div>

      <el-dialog
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        @close="evtDialogClose"
        lock-scroll
        :title="diaTitle"
        width="500px"
        append-to-body
      >
        <div v-loading="addloading">
          <div class="win-warp" style="height: 430px">
            <el-form
              :model="form"
              :rules="addRules"
              ref="addForm"
              size="small"
              label-width="80px"
            >
              <el-row class="row-bg" :gutter="22">
                <el-col :span="24">
                  <el-form-item label="维护类型" prop="typeId">
                    <el-select
                      v-model="form.typeId"
                      placeholder="请选择"
                      style="width: 100%"
                      @change="typeChange"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in maintenanceTypeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="维护日期" prop="repairDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.repairDate"
                      type="date"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择日期"
                      size="small"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="维护人" prop="repairUserName">
                    <el-input
                      v-model="form.repairUserName"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="维护记录" prop="repairLog">
                    <el-input
                      v-model="form.repairLog"
                      placeholder="请输入"
                      type="textarea"
                      :rows="3"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item
                    :label="'照片(' + fileListPic.length + '/6)'"
                    prop="buyDate"
                  >
                    <el-upload
                      class="avatar-uploader"
                      action="/api/file/upload"
                      list-type="picture-card"
                      :data="Imgdata"
                      accept="image/*"
                      :headers="headers"
                      :on-preview="handlePreview"
                      :before-upload="beforeAvatarUpload"
                      :on-remove="handleRemove"
                      :on-success="handleAvatarSuccess"
                      :before-remove="beforeRemove"
                      multiple
                      :limit="6"
                      :on-exceed="handleExceed"
                      :file-list="fileListPic"
                    >
                      <i class="el-icon-plus"></i>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false" size="small"
              >取 消</el-button
            >
            <el-button
              @click="addBtn()"
              type="primary"
              size="small"
              style="background: #00b38b; border: none"
              >确定</el-button
            >
          </div>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { equipmentApi } from "@/api/patrol/equipment";
import Token from "@/itsoftUI/auth/token.js";
import moment from "moment";

export default {
  props: ["maintenanceTypeList"],
  data() {
    return {
      dialogFormVisible: false,
      dialogTableVisible: false,
      addloading: false,
      searchObj: {
        dateData: [
          moment()
            .subtract(3, "months")
            .format("yyyy-MM-DD"),
          moment().format("yyyy-MM-DD"),
        ],
      },
      totalRows: 0,
      pageSize: 20,
      diaTitle: "新增", // 1新增 2编辑
      currentPage: 1,
      loading: false,
      search: [],
      tableData: [],
      deviceId: "",
      tableLoading: false,
      Imgdata: {
        system: "newRepair",
      },
      headers: {
        Token: "",
        TokenKey: "",
      },
      form: {
        name: "",
      },

      addRules: {
        typeId: [
          {
            required: true,
            message: "请选择维护类型",
            trigger: "blur",
          },
        ],
        repairDate: [
          {
            required: true,
            message: "请选择维护日期",
            trigger: "blur",
          },
        ],
        repairUserName: [
          {
            required: true,
            message: "请填写维护人",
            trigger: "blur",
          },
        ],
        repairLog: [
          {
            required: true,
            message: "请填写维护记录",
            trigger: "blur",
          },
        ],
      },
      fileListPic: [],
    };
  },
  methods: {
    //放大查看图片
    handlePreview(file) {
      var newwin = window.open();
      newwin.document.write("<img src=" + file.url + " />");
    },
    beforeAvatarUpload(file) {
      //文件上传之前调用做一些拦截限制
      this.headers.Token = Token.getToken();
      this.headers.TokenKey = Token.getTokenKey();
      const isJPG = true;
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 实物照片
    handleRemove(file, fileList) {
      let imgArr = [];
      this.fileListPic.forEach((item, key) => {
        if (item.url == file.url) {
          this.fileListPic.splice(key, 1);
        }
      });
      this.fileListPic.forEach((item) => {
        let str = item.url.replace(this.$itsoftUI.config.fileServer, "");
        imgArr.push(str);
      });
      this.form.pic = imgArr.join(",");
    },
    handleAvatarSuccess(file, fileList) {
      //实物照片
      let imgArr = [];
      let obj = {};
      obj.name = file.data.name;
      obj.url = this.$itsoftUI.config.fileServer + file.data.path;
      this.fileListPic.push(obj);
      this.fileListPic.forEach((item) => {
        let str = item.url.replace(this.$itsoftUI.config.fileServer, "");
        imgArr.push(str);
      });
      this.form.pic = imgArr.join(",");
    },
    beforeRemove() {
      return this.$confirm(`确定移除 ？`);
    },
    handleExceed() {
      this.$message.error("已达到上传最大数量");
    },
    typeChange() {
      this.form.typeName = this.maintenanceTypeList.find(
        (e) => e.id === this.form.typeId
      ).name;
    },
    evtDialogClose() {
      this.form = {};
      this.fileListPic = [];
    },
    addBtn() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.addloading = true;
          this.form.deviceId = this.searchObj.deviceId;
          equipmentApi.saveRepair(this.form).then((res) => {
            this.addloading = false;
            if (res.status == "success") {
              this.$message.success("提交成功");
              this.dialogFormVisible = false;
              this.addloading = false;
              this.$refs.addForm.clearValidate();
              this.$refs.addForm.resetFields();
              this.getTableList();
            }
          });
        } else {
          this.addloading = false;
          return false;
        }
      });
    },
    // 事件
    event(key) {
      switch (key) {
        case "add":
          this.dialogFormVisible = true;
          this.diaTitle = "新增";
          break;
        case "edit":
          if (!this.currentRow) {
            this.$message.error("请选中需要编辑的数据行");
            return;
          }
          this.getDetail();
          break;
        case "del":
          if (this.multipleSelection.length === 0) {
            this.$message.error("请选中要删除的数据");
            return;
          }
          this.del();
          break;
        case "code":
          this.dialogCode = true;
          this.getCodeList();
          break;
        default:
          break;
      }
    },
    getDetail() {
      this.dialogFormVisible = true;
      this.diaTitle = "编辑";
      this.addloading = true;
      equipmentApi
        .GetRepair(this.currentRow.id)
        .then((res) => {
          this.form = res.data;
          this.addloading = false;
          this.fileListPic = this.form.pic
            ? this.form.pic.split(",").map((e) => {
                return {
                  url: this.$itsoftUI.config.fileServer + e,
                };
              })
            : [];
        })
        .catch(() => {
          this.addloading = false;
        });
    },
    // 删除
    del() {
      this.$confirm("确定要删除当前选中的数据吗？", "删除", {
        distinguishCancelAndClose: true,
        confirmButtonText: "删除",
        cancelButtonText: "放弃删除",
      })
        .then(() => {
          let idList = [];
          for (let i = 0; i < this.multipleSelection.length; i++) {
            idList.push(this.multipleSelection[i].id);
          }
          var ids = idList.join(",");
          equipmentApi.DelRepair(ids).then((res) => {
            if ((res.status = "success")) {
              this.$message.success("删除成功");
              this.getTableList();
            }
          });
        })
        .catch(() => {
          this.$refs.dataListTable.clearSelection();
        });
    },
    // 组装条件
    setSearchData() {
      this.search = [];
      for (const key in this.searchObj) {
        const item = this.searchObj[key];
        if (item) {
          if (key === "name") {
            this.search.push({
              andOr: "and",
              searchField: key,
              operator: "like",
              searchValue: item,
            });
          } else if (key === "dateData") {
            this.search.push({
              andOr: "and",
              searchField: "repairDate",
              operator: ">=",
              searchValue: item[0],
            });
            this.search.push({
              andOr: "and",
              searchField: "repairDate",
              operator: "<=",
              searchValue: item[1],
            });
          } else {
            this.search.push({
              andOr: "and",
              searchField: key,
              operator: "=",
              searchValue: item,
            });
          }
        }
      }
    },
    getTableList() {
      this.setSearchData();
      let page = {
        pageIndex: this.currentPage,
        pageSize: this.pageSize,
      };
      this.tableLoading = true;
      equipmentApi
        .repairList(
          JSON.stringify(page),
          JSON.stringify(this.search),
          "repairDate desc"
        )
        .then((res) => {
          this.tableData = res.data.rows;
          this.totalRows = res.data.total;
          this.tableLoading = false;
        });
    },
    evtPageSizeChange(val) {
      //每页数量
      this.pageSize = val;
      this.getTableList();
    },
    evtPageCurrentChange(val) {
      //分页
      this.currentPage = val;
      this.getTableList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    tableDbEdit(currentRow) {
      //双击行
      this.currentRow = currentRow;
      this.getDetail();
    },
    evtTableRowChange(currentRow) {
      //单选行
      this.currentRow = currentRow;
    },
  },
  created() {},
};
</script>

<style lang="scss" scoped>
.headers {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
  .select {
    display: flex;
    column-gap: 10px;
  }
}
.btns {
  display: flex;
  column-gap: 12px;
  div {
    height: 32px;
    border-radius: 2px 2px 2px 2px;
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 1px 15px;
    cursor: pointer;
  }
  .add {
    background: #00b38b;
  }
  .edit {
    background: #3d83ff;
  }
  .del {
    background: #ff5c5e;
  }
  .ma {
    background: #3d83ff;
  }
  .userBatch,
  .user {
    color: #1d2129;
    border: 1px solid #c9cdd4;
  }
}
</style>
